package cn.itcast.bos.web.action;

import cn.itcast.bos.domain.base.FixedArea;
import cn.itcast.bos.domain.constant.Constants;
import cn.itcast.bos.service.FixedAreaService;
import cn.itcast.bos.web.action.common.BaseAction;
import cn.itcast.crm.domain.Customer;
import com.opensymphony.xwork2.ActionContext;
import org.apache.commons.lang3.StringUtils;
import org.apache.cxf.jaxrs.client.WebClient;
import org.apache.struts2.ServletActionContext;
import org.apache.struts2.convention.annotation.Action;
import org.apache.struts2.convention.annotation.Namespace;
import org.apache.struts2.convention.annotation.ParentPackage;
import org.apache.struts2.convention.annotation.Result;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Scope;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.stereotype.Controller;

import javax.persistence.criteria.CriteriaBuilder;
import javax.persistence.criteria.CriteriaQuery;
import javax.persistence.criteria.Predicate;
import javax.persistence.criteria.Root;
import javax.ws.rs.core.MediaType;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;

@ParentPackage(value="json-default")
@Namespace("/")
@Controller
@Scope("prototype")
public class FixedAreaAction extends BaseAction<FixedArea> {

	@Autowired
	private FixedAreaService fixedAreaService;
	
	/**分区保存*/
	@Action(value="fixedArea_save",results={@Result(name="success",type="redirect",location="./pages/base/fixed_area.html")})
	public String save(){
		fixedAreaService.save(model);
		return SUCCESS;
	}
	
	@Action(value="fixedArea_pageQuery",results={@Result(name="success",type="json")})
	public String pageQuery(){
		// 有条件的查询
		Pageable pageable = new PageRequest(page-1, rows);
		// 组织查询条件
		Specification<FixedArea> specification = new Specification<FixedArea>() {
			
			// 返回的Predicate对象封装结果集
			@Override
			public Predicate toPredicate(Root<FixedArea> root, CriteriaQuery<?> query, CriteriaBuilder cb) {
				
				Predicate predicate = null;
				// 用来封装查询条件（页面传递2个查询条件 ）
				List<Predicate> list = new ArrayList<Predicate>();
				// 定区id
				if(StringUtils.isNotBlank(model.getId())){
					Predicate p = cb.equal(root.get("id").as(String.class), model.getId());// id = ?
					list.add(p);
				}
				// 公司
				if(StringUtils.isNotBlank(model.getCompany())){
					Predicate p = cb.like(root.get("company").as(String.class), "%"+model.getCompany()+"%");// company like ?
					list.add(p);
				}
				
				// 方案二：表示存在查询条件（使用query）
				if(list!=null && list.size()>0){
					Predicate [] p = new Predicate[list.size()];
					query.where(list.toArray(p));
				}
				// 按照id降序排列
				query.orderBy(cb.desc(root.get("id").as(String.class)));
				
				return query.getRestriction();// 返回结果
			}
		};
		Page<FixedArea> page = fixedAreaService.findPageQueryCondition(specification, pageable);
		pushPageDataToValueStack(page);
		
		return SUCCESS;
	}

	@Action(value = "fixedArea_noassociationSelect",results = {@Result(name = SUCCESS,type = "json")})
	public String noassociationSelect(){
		Collection<? extends Customer> collection = WebClient.create(Constants.CRM_MANAGEMENT_URL+"/services/customerService")
				.path("/findNoAssociationCustomers")
				.accept(MediaType.APPLICATION_JSON)
				.getCollection(Customer.class);
		ActionContext.getContext().getValueStack().push(collection);
		return SUCCESS;
	}


    // 使用当前定区查询当前定区关联的客户
    @Action(value="fixedArea_associationSelect",results={@Result(name="success",type="json")})
    public String associationSelect(){
        Collection<? extends Customer> collection = WebClient.create(Constants.CRM_MANAGEMENT_URL + "/services/customerService/findHasAssociationCustomers/" + model.getId())
               // .type(MediaType.APPLICATION_JSON)
                .accept(MediaType.APPLICATION_JSON)
                .getCollection(Customer.class);
        ServletActionContext.getContext().getValueStack().push(collection);
        return SUCCESS;
    }

    private String [] customerIds;

    public void setCustomerIds(String[] customerIds) {
        this.customerIds = customerIds;
    }

    // 点击，定区关联客户（webservice）
    @Action(value="fixedArea_associationCustomersToFixedArea",results={@Result(name="success",type="redirect",location="./pages/base/fixed_area.html")})
    public String associationCustomersToFixedArea(){
        // 将数组的值，转换成字符串，并且多个值中间使用逗号分开
        String customerIdStr = StringUtils.join(customerIds, ",");
        WebClient.create(Constants.CRM_MANAGEMENT_URL+"/services/customerService/associationCustomersToFixedArea?customerIdStr="+customerIdStr+"&fixedAreaId="+model.getId())
                .type(MediaType.APPLICATION_JSON)// type表示参数（传递xml格式的参数）
                .put(null);
        return SUCCESS;
    }

    //获取属性
    //快递员ID
    private String courierId;
    //取派时间ID
    private String takeTimeId;

    public void setCourierId(String courierId) {
        this.courierId = courierId;
    }

    public void setTakeTimeId(String takeTimeId) {
        this.takeTimeId = takeTimeId;
    }

    //点击,定区关联快递员
    @Action(value = "fixedArea_associationCourierToFixedArea",results = {@Result(name = SUCCESS,type = "redirect",location = "./pages/base/fixed_area.html")})
    public String associationCourierToFixedArea(){
        fixedAreaService.associationCourierToFixedArea(model.getId(),courierId,takeTimeId);
        return SUCCESS;
    }




}
